package ml.uuku.oschub.fragment;

import ml.uuku.oschub.adpater.ListBaseAdapter;
import ml.uuku.oschub.adpater.NewsAdapter;
import ml.uuku.oschub.api.remote.OSChinaApi;
import ml.uuku.oschub.base.BaseListFragment;
import ml.uuku.oschub.bean.News;
import ml.uuku.oschub.bean.NewsList;
import ml.uuku.oschub.interf.OnTabReselectListener;
import ml.uuku.oschub.ui.empty.EmptyLayout;
import ml.uuku.oschub.util.XmlUtils;

import java.io.InputStream;
import java.io.Serializable;
import java.util.List;

/**
 * @author <a href=http://my.oschina.net/uuku>uuku</a>
 * @version V0.1
 */
public class NewsFragment extends BaseListFragment<News> implements OnTabReselectListener {
    protected static final String TAG = NewsFragment.class.getSimpleName();
    private static final String CACHE_KEY_PREFIX = "newslist_";

    @Override
    protected NewsAdapter getListAdapter() {
        return new NewsAdapter();
    }

    @Override
    protected NewsList parseList(InputStream is) throws Exception {
        NewsList list = null;
        try {
            list = XmlUtils.toBean(NewsList.class, is);
        } catch (NullPointerException e) {
            list = new NewsList();
        }
        return list;
    }

    @Override
    protected NewsList readList(Serializable seri) {
        return ((NewsList) seri);
    }

    @Override
    protected void sendRequestData() {
        OSChinaApi.getNewsList(mCatalog, mCurrentPage, mHandler);
    }

    @Override
    protected void executeOnLoadDataSuccess(List<News> data) {
        if (mCatalog == NewsList.CATALOG_WEEK
                || mCatalog == NewsList.CATALOG_MONTH) {
            mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
            if (mState == STATE_REFRESH)
                mAdapter.clear();
            mAdapter.addData(data);
            mState = STATE_NOMORE;
            mAdapter.setState(ListBaseAdapter.STATE_NO_MORE);
            return;
        }
        super.executeOnLoadDataSuccess(data);
    }

    @Override
    public void onTabReselect() {
        onRefresh();
    }
}
